import { Toast } from "antd-mobile";
import { useAuthStore2 } from "@/app/cg06/store/useAuthStore2";
import { getUrlParams } from "./baseInfo";
import { useRouter } from "next/navigation";

const urlMap = {
  development: "https://uat-wms.zmetaport.com",
  dev: "https://dev-wms.zmetaport.com",
  staging: "https://uat-wms.zmetaport.com",
  prod: "https://wms.zmetaport.com",
};
const env = (process.env.NEXT_PUBLIC_APP_ENV || "prod") as
  | "dev"
  | "staging"
  | "prod";

const envTest =
  typeof window !== "undefined" &&
  (new URL(window.location.href).searchParams.get("env") as typeof env);

console.log(envTest, "envTest", env);
const envFinale = env == "prod" ? env : envTest || env;
const url = urlMap[envFinale];
export { url as remote, envFinale, env };
export interface ResDataType<T = unknown> {
  code: string;
  msg: string;
  data?: T;
  rows?: T;
}

export type HTTP_METHOD = "GET" | "POST" | "DELETE";

type Config = {
  tokenRequired: boolean;
};

/**
 *
 * @param path /a/b/c
 * @returns res.data
 */
export function fetchWrapper<T = unknown>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: HTTP_METHOD = "GET",
  config?: Config
): Promise<T | undefined> {
  return fetchWithAuth<ResDataType<T>>(path, data, method, config).then(
    (r) => r.data || r.rows
  );
}

export function fetchWithAuth<T extends ResDataType>(
  path: string,
  data?: Record<string, unknown> | unknown[],
  method: "GET" | "POST" | "DELETE" = "GET",
  config?: Config
): Promise<T> {
  const store = useAuthStore2.getState();
  const token = store.token;
  const { tokenRequired = true } = config || {};
  if (!token && tokenRequired) throw new Error("No Token");

  const wearhouseId = getUrlParams("warehouseId") || "102743510335520";

  // path 是 http 开头的直接请求
  const Url = path.startsWith("http") ? path : `${url}${path}`;

  return fetch(Url, {
    headers: {
      Authorization: `Bearer ${token}`,
      Warehouseid: wearhouseId || "",
      ...(data ? { "content-type": "application/json" } : {}),
    },
    method,
    ...(data ? { body: JSON.stringify(data) } : {}),
  }).then((res) =>
    res.json().then((r) => {
      if (r.code != 200) {
        if (r.code == 401) {
          if (store.token && token === store.token) {
            store.setToken("");
            // window.location.href = process.env.NEXT_PUBLIC_APP_ENV === 'development' ? '/cg06/login' : '/cg06/login.html'
          }
          throw r;
        }
        Toast.show(r.msg || "接口出错");
        throw r;
      }
      return r as T;
    })
  );
}
